package com.hgxd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hgxd.entity.pojo.AlarmMsg;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgxd.exception.ServiceException;
import com.hgxd.mapper.AlarmMsgMapper;
import com.hgxd.result.ResultCodeEnum;
import com.hgxd.service.IAlarmMsgService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报警列表 服务实现类
 * </p>
 *
 * @author fsd
 * @since 2023-10-18
 */
@Service("AlarmMsgServiceImpl")
public class AlarmMsgServiceImpl extends ServiceImpl<AlarmMsgMapper, AlarmMsg> implements IAlarmMsgService {

    @Resource
    private AlarmMsgMapper alarmMsgMapper;

    @Override
    public Boolean publishById(AlarmMsg alarmMsg) {
        if (alarmMsg.getId() == null || alarmMsg.getId() == 0) {
            throw new ServiceException(ResultCodeEnum.ARGUMENT_VALID_ERROR, "无效参数:id");
        }
        return alarmMsgMapper.updateById(alarmMsg) == 1;
    }

    @Override
    public Map<String, Object> getAlarmMsgTody() {
        LocalDateTime nowDateTime = LocalDateTime.now();
        // 获取当天最开始时间
        LocalDateTime beginningOfDay = nowDateTime.toLocalDate().atStartOfDay();

        // 获取当天最后时间
        LocalDateTime endOfDay = nowDateTime.toLocalDate().atTime(LocalTime.MAX);

        // 根据时间查出当天所有的报警信息
        LambdaQueryWrapper<AlarmMsg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(AlarmMsg::getAlarmTime, beginningOfDay, endOfDay);
        List<AlarmMsg> alarmMsgList = alarmMsgMapper.selectList(queryWrapper);

        // 构造返回结构
        HashMap<String, Object> map = new HashMap<>();

        // 判断有无报警信息
        if (alarmMsgList.isEmpty()) {
            map.put("total", 0);
            map.put("okCount", 0);
            map.put("ngCount", 0);
            map.put("percentage", 100);
        } else {
            // 算出报警总量 解决量 未解决量 已解决百分比
            long okCount = alarmMsgList.stream()
                    .filter(alarmMsg -> "已解决".equals(alarmMsg.getAlarmStatus())).count();
            long ngCount = alarmMsgList.stream()
                    .filter(alarmMsg -> "未解决".equals(alarmMsg.getAlarmStatus())).count();
            BigDecimal bigDecimal = BigDecimal.valueOf((double) okCount / (double) alarmMsgList.size() * 100);
            BigDecimal percentageDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);
            double percentage = percentageDecimal.doubleValue();
            map.put("total", alarmMsgList.size());
            map.put("okCount", okCount);
            map.put("ngCount", ngCount);
            map.put("percentage", percentage);
        }
        return map;
    }
}
